import 'package:aichat_flutter_wallet/module/module_create_wallet/model/mnemonic.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/bottom_button.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/error_tip_widget.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_util/lib_util.dart';

import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/Routers.dart';

class VerifyMnemonicPage extends StatefulWidget {
  const VerifyMnemonicPage({super.key});

  @override
  State<VerifyMnemonicPage> createState() => _VerifyMnemonicPageState();
}

class _VerifyMnemonicPageState extends State<VerifyMnemonicPage> {
  List<String> list = [];
  List<String> selectList = [];
  Map<String, bool> selectMap = {};
  bool canConfirm = false;
  late String mnomenicKey;
  late bool isCheckRight;
  bool showError = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    int wallet_id = MnemonicData().walletId;
    mnomenicKey = MnemonicData.getMnemonic(wallet_id);
    list = MnemonicData.disrupteKey(mnomenicKey);
  }

  addSelectList(String str) {
    setState(() {
      bool yes = selectList.any((element) => element == str);
      if (!yes) {
        selectList.add(str);
        selectMap[str] = true;
        if (selectList.length == 12) {
          canConfirm = true;
        }
      }
    });
  }

  removeSelectList(String str) {
    setState(() {
      selectList.removeWhere((element) => element == str);
      selectMap.remove(str);
      canConfirm = false;
    });
  }

  // 验证助记词
  void checkMnemonic() {
    String key = selectList.join(' ');
    if (key != mnomenicKey) {
      if (showError) return;
      setState(() {
        showError = true;
      });
    } else {
      Toast.show(context, message: 'Successful Operation', position: Dpositon.bottom);
      context.read<WalletInfoNotifier>().updateWalletBackupState(MnemonicData().walletId);
      Navigator.pushNamedAndRemoveUntil(
        context,
        Routes.rootAssetsPage, // 要跳转的新路由名称
        (route) => false, // 移除所有路由记录
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: PageHeaderCom(
        title: 'Verify Recovery Phrase',
        showBottomBorder: false,
      ),
      body: Stack(
        children: [
          Padding(
            padding: EdgeInsets.only(left: 20.0.w, right: 20.w, top: 10.w),
            child: SingleChildScrollView(
              child: Stack(
                children: [
                  Column(
                    children: [
                      Container(
                        child: Text(
                            'Tap the phrases and put them together in the correct order to check that your recovery phrase is correct.'),
                      ),
                      SizedBox(
                        height: 20.w,
                      ),
                      Container(
                        height: 240.w,
                        padding: EdgeInsets.all(10.w),
                        width: double.infinity,
                        decoration: BoxDecoration(color: AppColors.c_F6F6F6, borderRadius: BorderRadius.circular(10.w)),
                        child: Wrap(
                          spacing: 12.w,
                          runSpacing: 10.w,
                          children: List.generate(selectList.length, (index) {
                            return GestureDetector(
                              onTap: () {
                              },
                              child: Stack(
                                clipBehavior: Clip.none,
                                children: [
                                  Container(
                                    width: 92.w,
                                    height: 47.w,
                                    padding: EdgeInsets.only(
                                      left: 10.w,
                                    ),
                                    decoration: BoxDecoration(
                                        border: Border.all(width: 1.w, color: AppColors.c_BEBDCA),
                                        borderRadius: BorderRadius.circular(10.w)),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          "${index + 1}",
                                          style: TextStyle(
                                              fontSize: 12.sp, color: AppColors.c_BEBDCA, fontWeight: FontWeight.w400),
                                        ),
                                        Text(
                                          "${selectList[index]}",
                                          style: TextStyle(
                                              fontSize: 14.sp, color: AppColors.c_333333, fontWeight: FontWeight.w400),
                                        ),
                                      ],
                                    ),
                                  ),
                                  if (index == selectList.length - 1)
                                    Positioned(
                                      child: GestureDetector(
                                        onTap: () {
                                          removeSelectList(selectList[index]);
                                        },
                                        child: Image(
                                          image: AssetImage('assets/images/wallet/close.png'),
                                          width: 20.w,
                                          height: 20.w,
                                        ),
                                      ),
                                      right: -5.w,
                                      top: -5.w,
                                    )
                                ],
                              ),
                            );
                          }),
                        ),
                      ),
                      SizedBox(
                        height: 10.w,
                      ),
                      Container(
                        width: double.infinity,
                        child: Wrap(
                          spacing: 12.w,
                          runSpacing: 10.w,
                          alignment: WrapAlignment.spaceBetween,
                          children: List.generate(list.length, (index) {
                            return GestureDetector(
                              onTap: () {
                                addSelectList(list[index]);
                              },
                              child: Container(
                                height: 40.w,
                                width: 90.w,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        width: 1,
                                        color: selectMap.containsKey(list[index])
                                            ? AppColors.c_F6F6F6
                                            : AppColors.c_BEBDCA),
                                    borderRadius: BorderRadius.circular(10.w)),
                                child: Text(
                                  "${list[index]}",
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      color:
                                          selectMap.containsKey(list[index]) ? AppColors.c_BEBDCA : AppColors.c_333333,
                                      fontWeight: FontWeight.w400),
                                ),
                              ),
                            );
                          }),
                        ),
                      ),
                      SizedBox(
                        height: 100.w,
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          if (showError)
            Positioned(
              bottom: 80.w,
              left: 20.w,
              right: 20.w,
              child: ErrorTipWidget(
                tips: 'Mnemonic words in wrong order',
                onClose: () {
                  setState(() {
                    showError = false;
                  });
                },
              ),
            ),
          Positioned(
              bottom: 10.w,
              left: 20.w,
              right: 20.w,
              child: BottomBtn(
                textList: ['Confirm'],
                disable: !canConfirm,
                onConfirm: () {
                  checkMnemonic();
                },
                onDisableClick: () {},
              )),
        ],
      ),
    );
  }
}
